package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {
    @Autowired
    private EmpExprService empExprService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {
        //保存员工信息，保存员工经历信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        this.save(emp);
        Integer empId = emp.getId();
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(expr->expr.setEmpId(empId));
        empExprService.saveBatch(exprList);

    }

    @Override
    public Emp getEmpById(Integer id) {
        Emp emp = this.getById(id);
        if(emp == null){
            throw new RuntimeException("数据库数据不存在");
        }
        List<EmpExpr> list = empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId,emp.getId()));
        emp.setExprList(list);
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        //更新员工数据
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);
        //更新经验表数据，先删除,再添加
        boolean remove = empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        List<EmpExpr> exprList = emp.getExprList();
        if(exprList!=null && exprList.size()>0){
            exprList.forEach(expr->expr.setEmpId(emp.getId()));
            empExprService.saveBatch(exprList);
        }


    }

    @Override
    public void removeByEmpIds(List<Integer> ids) {
        this.removeBatchByIds(ids);

        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId,ids));

    }
}
